<template>
  <basic-container>
    <el-row :gutter="10">
      <el-col :span="4">
        <el-tree :data="treeData" :load="loadNode" lazy node-key="id" @node-click="handleNodeClick"
          :default-expanded-keys="defaultExpandedKeys" />
      </el-col>
      <el-col :span="20" class="rightColumn">
        <avue-crud v-if="!currentId || currentId == -1" :option="option1" v-model:search="search" v-model:page="page"
          v-model="form" :upload-before="uploadBefore" :table-loading="loading" :data="data"
          :permission="permissionList" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
          @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
          @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
        </avue-crud>
        <avue-crud v-else :option="option" v-model:search="search" v-model:page="page" v-model="form"
          :upload-before="uploadBefore" :table-loading="loading" :data="data" :permission="permissionList" ref="crud"
          @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange"
          @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
          @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
          <template #test="record">
            <div>
              <el-tag v-for="item in website.knowledgeLevelLists" :key="item.value"
                @click="gotoCourseware(item.value, record)">{{ item.label }}</el-tag>
            </div>
          </template>
          <template #menu-left="scope">
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删 除</el-button>
          </template>
          <template #menu-right="scope">
            <el-button type="default" icon="el-icon-upload" plain circle class="upload">
              <input type="file" @change="handleImport" ref="file" class="hideFileInput" accept=".xlsx" />
            </el-button>
          </template>
          <template #name="scope">
            <el-tag @click="openDialog(scope)">{{ scope.row.name }}</el-tag>
          </template>
          <template #file="scope">
            <el-image style="width: 100px; height: 100px" :src="url + scope.row.attach.id" fit="scale-down" />
          </template>
          <template #menu="scope">
            <el-button type="primary" link icon="DocumentChecked" @click="openPubModel(scope)">
              发 布
            </el-button>
            <el-button type="primary" link icon="DocumentDelete" @click="openUnpubModel(scope)">
              取消发布
            </el-button>
          </template>
        </avue-crud>
      </el-col>
    </el-row>
    <el-dialog v-model="dialogVisible" :title="Tips" width="500">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="序号" width="180" />
        <el-table-column prop="posi" label="岗位" />
      </el-table>
      <div class="flex flex-end mt10">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </el-dialog>
    <Dialog :data="currentData" ref="child" @close="visible = false" />
    <!-- <div>
              <el-popover
                placement="bottom"
                trigger="click"
                :width="500"
                @before-enter="handlePublish(0,scope)"
              >
                <template #reference>
                  <el-button type="primary" link icon="DocumentChecked">发 布</el-button>
                </template>
                <h3>该知识点已在如下岗位中引用，请确认是否发布</h3>
                <el-table :data="tableData" style="width: 100%">
                  <el-table-column prop="id" label="ID" width="180" />
                  <el-table-column prop="posi" label="岗位" />
                </el-table>
                <div class="flex flex-end mt10">
                  <el-button type="primary" @click="handlePublish(1,scope)">确认</el-button>
                </div>
              </el-popover>
              <el-popover
                placement="bottom"
                trigger="click"
                :width="500"
                @before-enter="handleUnPublish(0)"
              >
                <template #reference>
                  <el-button type="primary" link icon="DocumentDelete">取消发布</el-button>
                </template>
                <h3>该知识点已在如下岗位中引用，请确认是否取消发布</h3>
                <el-table :data="tableData" style="width: 100%">
                  <el-table-column prop="id" label="ID" width="180" />
                  <el-table-column prop="posi" label="岗位" />
                </el-table>
                <div class="flex flex-end mt10">
                  <el-button type="primary" @click="handleUnPublish(1)">确认</el-button>
                </div>
              </el-popover>
            </div> -->
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import {
  getKnowledgeList,
  saveKnowledge,
  updateKnowledge,
  removeKnowledge,
  publishCourseware,
  unPublishCourseware,
} from '@/api/position/knowledge';
import { getList, publish, unpublish } from '@/api/position/knowledgeClassification';
import option from '@/option/position/knowledge';
import option1 from '@/option/position/knowledge1';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import Dialog from './dialogCopy.vue';

export default {
  components: {
    Dialog,
  },
  data() {
    return {
      treeData: [],
      currentId: '-1',
      option,
      option1,
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      data: [],
      file: null,
      currentData: {
        data: {},
        form: {},
        crud: [],
      },
      tableData: [],
      dialogVisible: false,
      Tips: '',
      defaultExpandedKeys: [],
      url: this.baseHost + '/blade-resource/oss/endpoint/viewFile/'
    };
  },
  created() {
    this.option.column[3].dicData = this.website.securityLists;
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        editBtn: true,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    openPubModel({ row }) {
      this.handlePublish(0, row);
      this.currrow = row;
      this.Tips = '该知识点已在如下岗位中引用，请确认是否发布';
    },
    openUnpubModel({ row }) {
      this.handleUnPublish(0, row);
      this.currrow = row;
      this.Tips = '该知识点已在如下岗位中引用，请确认是否取消发布';
    },
    getTreeData(parentId = { parentId: '-1' }, resolve) {
      getList(1, 100, parentId).then(res => {
        const data = res.data.data.records.map(item => {
          return {
            id: item.id,
            label: item.name,
            children: [],
          };
        });
        if (!this.treeData.length) {
          this.treeData = [
            {
              id: '-1',
              label: '知识分类',
              children: data,
            },
          ];
          this.defaultExpandedKeys = ['-1'];
        } else if (resolve) {
          resolve(data);
        }
      });
    },
    loadNode(node, resolve) {
      this.currentId = node.data.id;
      this.file = null;
      this.getTreeData(
        {
          parentId: node.data.id,
        },
        resolve
      );
    },
    rowSave(row, done, loading) {
      if (!row.parentId) {
        row.parentId = -1;
      }
      const formdata = new FormData();

      if (row.name) {
        formdata.append('name', row.name);
      }
      if (row.note) {
        formdata.append('note', row.note);
      }
      if (row.security) {
        formdata.append('security', row.security);
      }
      if (this.file) {
        formdata.append('file', this.file);
      }
      formdata.append('classificationId', this.currentId || '-1');

      saveKnowledge(formdata).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const formdata = new FormData();
      if (row.name) {
        formdata.append('name', row.name);
      }
      if (row.note) {
        formdata.append('note', row.note);
      }
      if (row.security) {
        formdata.append('security', row.security);
      }
      if (this.file) {
        formdata.append('file', this.file);
      }
      if (this.currentId) {
        formdata.append('classificationId', this.currentId);
      } else {
        formdata.append('classificationId', '-1');
      }
      formdata.append('id', row.id);
      updateKnowledge(formdata).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeKnowledge(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const p = [];
        this.selectionList.forEach(item => p.push(removeKnowledge(item.id)));
        Promise.all(p).then(res => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
      });
    },
    handleImport(file) {
      if (!file.target.files[0].name.includes('xlsx')) {
        this.$message({
          type: 'error',
          message: '导入数据有误，请导入xlsx格式的文件！',
        });
        return;
      }
      NProgress.start();
      const reader = new FileReader();
      reader.onload = e => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const sheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(sheet);
        const p = [];
        jsonData.forEach(json => {
          const formdata = new FormData();
          if (json['知识点名称']) {
            formdata.append('name', json['知识点名称']);
          }
          if (json['知识点描述']) {
            formdata.append('note', json['知识点描述']);
          }
          if (json['封面图']) {
            formdata.append('file', json['封面图']);
          }
          if (json['密级']) {
            const data = this.website.securityLists.find(item => item.label == json['密级']);
            if (data) {
              formdata.append('security', data.value);
            }
          }
          if (this.currentId) {
            formdata.append('classificationId', this.currentId);
          } else {
            formdata.append('classificationId', '-1');
          }
          p.push(saveKnowledge(formdata));
        });
        Promise.all(p)
          .then(res => {
            NProgress.done();
            this.$message.success('导入成功');
            this.onLoad(this.page);
          })
          .catch(err => {
            this.$message.error('导入失败');
          });
        this.$refs.file.value = '';
      };
      reader.readAsBinaryString(file.target.files[0]);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.data = [];
      let values = {
        classificationId: -1,
      };
      const { id, name, status } = this.query;
      if (id) {
        values.classificationId = id;
      }
      if (!id || id == '-1') {
        getList(1, 100, { parentId: '-1' }).then(res => {
          console.log(333, res.data.data);
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
        return;
      }
      if (name) {
        values['name'] = name;
      }
      if (status) {
        values['status'] = status;
      }
      if (this.currentId) {
        values.classificationId = this.currentId;
      }
      if (params.id) {
        values.classificationId = params.id;
      }

      getKnowledgeList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(item => {
          return {
            ...item,
            security: String(item.security),
            status: String(item.status),
          };
        });
        this.loading = false;
        this.selectionClear();
      });
    },
    handlePublish(type, row) {
      let params = {
        id: row.id,
      };
      if (type) {
        params['confirm'] = 'true';
      }
      publishCourseware(params)
        .then(res => {
          this.$message.success('发布成功');
          this.onLoad(this.page);
          this.dialogVisible = false;
        })
        .catch(res => {
          if (res.data.code == 999) {
            this.dialogVisible = true;
            this.tableData = res.data.data.map((item, index) => ({
              id: index + 1,
              posi: item.name,
            }));
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleConfirm() {
      if (this.Tips == '该知识点已在如下岗位中引用，请确认是否发布') {
        this.handlePublish(1, this.currrow);
      } else {
        this.handleUnPublish(1, this.currrow);
      }
    },
    handleUnPublish(type, row) {
      let params = {
        id: row.id,
      };
      if (type) {
        params['confirm'] = 'true';
      }
      unPublishCourseware(params)
        .then(res => {
          this.$message.success('取消成功');
          this.onLoad(this.page);
          this.dialogVisible = false;
        })
        .catch(res => {
          if (res.data.code == 999) {
            this.dialogVisible = true;
            this.tableData = res.data.data.map((item, index) => ({
              id: index + 1,
              posi: item.name,
            }));
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    handleNodeClick(row) {
      this.currentId = row.id;
      this.file = null;
      this.query = row;
      this.onLoad(this.page, row);
    },
    uploadBefore(file, callback, loading) {
      this.file = file;
      loading();
      const reader = new FileReader();
      const that = this;
      reader.onload = function (result) {
        const url = result.target.result;
        that.form.file = [url];
      };
      reader.readAsDataURL(file);
      return true;
    },
    gotoCourseware(type, data) {
      sessionStorage.setItem('question', JSON.stringify({
        id: data.row.id,
        name: data.row.name,
        type,
      }))
      this.$router.push({
        path: '/question',
      });
    },
    openDialog(data) {
      this.currentData.data = data.row;
      this.$refs.child.open();
    },
  },
};
</script>

<style>
.rightColumn .el-tag {
  cursor: pointer;
}

.rightColumn .el-tag:nth-child(2) {
  margin: 0 5px;
}

.flex {
  display: flex;
}

.flex-end {
  justify-content: flex-end;
}

.mt10 {
  margin-top: 10px;
}
</style>
